#server_tcp 服务器编程
import socket,threading,time


class SocketServer(object):
	def __init__(self,ip,port):		
		self._ip = ip
		self._port = int(port)
		self.max = 1024
		self.createSocket()
		
	def createSocket(self):
		self._sk = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
		self._sk.bind((self._ip,self._port)) #开始监听地址端口
		self._sk.listen(5) #传入的参数指定等待连接的最大数量：5
		print('socket create: %s:%s waiting for connectton ..'%(self._ip,self._port))
		while True:			
			cur_client,addr = self._sk.accept()			
			if cur_client and addr:
				print('创建线程addr=',addr)
				t = threading.Thread(target=self.tcpLink,args=(cur_client,addr)) #每个客户端就是一个线程(必须多线程或多进程才能同时处理)
				t.start()
			
	def tcpLink(self,cur_client,addr):
		servHead = 'S2C_Hello_'
		print('收到新的客户端请求%s')	
		cData = cur_client.recv(self.max).decode('utf-8')
		print('-------=cData:',cData)		
		wellcome = servHead+'wellcome to server tcp!'
		cur_client.send(wellcome.encode('utf-8')) #收到客户端消息,先发送一条欢迎语句给客户端
		while True:
			cData = cur_client.recv(self.max).decode('utf-8')
			time.sleep(0.5)
			print('tcpLink datahandler:',cData)
			if not cData or cData=='Q':
				break
			sData = servHead+cData
			sData = sData.encode('utf-8')
			cur_client.send(sData) #服务器发送回去给客户端
			print('send to client.......... sData:',sData)
		#cur_client.close() #关闭当前客户端socket
		#print('发送完数据关闭当前客户端-------------')



if __name__ == "__main__":
	print("this is socket server connecting .... ")
	ip = '127.0.0.1' #input('ip addr:')
	port = '9999' #input('port:')
	SocketServer(ip,port)
	